% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Replication "Deconstructing the Yield Curve"
% Crump and Gospodinov (2024)
% Date: 26-JUL-2024
% Code for implementing EWC variance estimator as in LLSW2018
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function output = ewc(Y,X,B)
    T = size(X,1) ;
    K = size(X,2) ;

    B = round(B) ;
    
    betahat = (X'*X)\(X'*Y) ;  
    ehat = Y - X*betahat ;
    
    Z = X.*(ehat*ones(1,K)) ;
    
    Omegahat = zeros(K,K) ;
    for b = 1:B
        Lambda_j = zeros(K,1) ;
        for t = 1:T
            Lambda_j = Lambda_j + sqrt(2/T)* Z(t,:)' * cos(pi*b*((t-.5)/T)) ;
        end 
        Omegahat = Omegahat + (1/B)*(Lambda_j*Lambda_j') ;
    end
     
    Vhat = inv(X'*X/T)*Omegahat*inv(X'*X/T) ;
    
    output.betahat = betahat ;
    output.Vhat = Vhat ;
    output.that = sqrt(T)*betahat./sqrt(diag(Vhat));
end